package com.viphome.util;


import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Created by wangzhanjin on 2017/12/20.
 * JDBC工具类：
 * （1）获取Connection
 * （2）释放资源
 */
public class JDBCUtil {

    /**
     * 获取Connection
     * @return 所获得到的JDBC的Connection
     */
    public static Connection getConnection() throws  Exception{

        //不建议配置硬编码
//        String url = "jdbc:mysql://119.23.237.202:3306/spring_data";
//        String user = "root";
//        String password = "Wzj123456++";
//        String driverClass = "com.mysql.jdbc.Driver ";
        InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        String url = (String)properties.get("jdbc.url");
        String user = (String)properties.get("jdbc.username");
        String password = (String)properties.get("jdbc.password");
        String driverClass = (String)properties.get("jdbc.driver");

        Class.forName(driverClass);
        Connection connection = DriverManager.getConnection(url, user, password);
        return connection;
    }

    /**
     * 释放DB相关的资源
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void release(ResultSet resultSet,
                               Statement statement,Connection connection){
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
